//
//  MallShopCartViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/7.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "MallShopCartViewController.h"
#import "MallCartTableViewCell.h"
#import "CartGoods.h"
#import "Goods.h"

@interface MallShopCartViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *cartArr;
@property (nonatomic, strong) NSMutableArray *selectArr;
@property (nonatomic, strong) NSMutableArray *goodIdArr;

@end

@implementation MallShopCartViewController {
    UITableView *_tableView;
    MallCartTableViewCell *_cell;
    
    UIView          *_bottomBgView;
    UIButton        *_allSelect;
    UILabel         *_goodMoney;
    UIButton        *_payment;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self GETMallCart];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self buildUI];
    [self refreshData];
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        [weakSelf GETMallCart];
    }];
    
    
}


#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    self.navigationItem.title = @"购物车";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(navRightClick:)];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-49-64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.sectionHeaderHeight = 40;
    _tableView.sectionFooterHeight = 10;
    
    [_tableView registerNib:[UINib nibWithNibName:@"MallCartTableViewCell" bundle:nil] forCellReuseIdentifier:@"cart"];
    
    _bottomBgView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-64-49, SCREEN_HEIGHT, 89)];
    [self.view addSubview:_bottomBgView];
    _bottomBgView.backgroundColor = kWhiteColor;
    
    _payment = [UIButton buttonWithType:UIButtonTypeCustom];
    [_bottomBgView addSubview:_payment];
    _payment.frame = CGRectMake(SW(4)*3, 0, SW(4), 49);
    _payment.backgroundColor = UIMainColorRGB;
    _payment.titleLabel.font = kUHSystemFontWithSize(12);
    [_payment setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [_payment setTitle:@"结算" forState:UIControlStateNormal];
//    [_payment addTarget:self action:@selector(paymentClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _allSelect = [UIButton buttonWithType:UIButtonTypeCustom];
    [_bottomBgView addSubview:_allSelect];
//    [_allSelect setImage:IMAGE(@"placeHolder") forState:UIControlStateNormal];
    [_allSelect setTitle:@"全选" forState:UIControlStateNormal];
    [_allSelect setTitleColor:kGrayColor forState:UIControlStateNormal];
    _allSelect.titleLabel.font = kUHSystemFontWithSize(12);
    CGSize btnSize = [LZCTools textSizeWithText:_allSelect.titleLabel.text font:kUHSystemFontWithSize(12)];
    _allSelect.frame = CGRectMake(10, 0, btnSize.width+5+30, 30);
    _allSelect.centerY = 24.5;
    [_allSelect setImage:IMAGE(@"shop_car_unchose") forState:UIControlStateNormal];
    [_allSelect setImage:IMAGE(@"shop_car_chose") forState:UIControlStateSelected];
    
    
    _goodMoney = [[UILabel alloc] init];
    [_bottomBgView addSubview:_goodMoney];
//    _goodMoney.text = [NSString stringWithFormat:@"合计:%.2lf(免运费)", [[[self.order valueForKey:@"items"][0] valueForKey:@"total_price"] floatValue]/100];
    _goodMoney.text = @"总价:0.00元";
    _goodMoney.textColor = kGrayColor;
    _goodMoney.font = kUHSystemFontWithSize(12);
    _goodMoney.frame = CGRectMake(SW(4), 0, SW(2)-10, 49);
    _goodMoney.textAlignment = NSTextAlignmentRight;
    
    
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _cell = [tableView dequeueReusableCellWithIdentifier:@"cart" forIndexPath:indexPath];
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSDictionary *dict = self.cartArr[indexPath.section][@"goodslist"][indexPath.row];
    Goods *model = [[Goods alloc] init];
    [model setValuesForKeysWithDictionary:dict];
    _cell.model = model;
    
    _cell.select.tag = indexPath.row+1;
    
    [_cell.increase addActionWithblock:^{
        _cell.num.text = [NSString stringWithFormat:@"%d", [_cell.num.text intValue]+1];
        
        
    }];

//    [_cell.select addTarget:self action:@selector(goodClick:) forControlEvents:UIControlEventTouchUpInside];
//    [_cell.select addActionWithblock:^{
//        
//        NSLog(@"+++++%d", _cell.select.isSelected);
//        
//        _cell.select.selected = !_cell.select.isSelected;
////        _cell.isS = _cell.select.isSelected;
////        
//        NSLog(@"%d", _cell.select.isSelected);
//        
////        sender.selected = !sender.isSelected;
////        
//        if (_cell.select.isSelected == YES) {
//            [_cell.select setImage:[IMAGE(@"login_tick") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
//        }
//        else {
//            [_cell.select setImage:[IMAGE(@"login_un_tick") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
//        }
//    }];
//    
    
//    if (_cell.select.isSelected == YES) {
//        [_cell.select setImage:[IMAGE(@"login_tick") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
//    }
//    else {
//        [_cell.select setImage:[IMAGE(@"login_un_tick") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateSelected];
//    }
    
    // 保存按钮
//    if (self.selectArr.count > 0 && ![self.goodIdArr containsObject:[model valueForKey:@"goods_id"]]) {
//        NSMutableArray *mArr = self.selectArr[indexPath.section];
//        NSMutableArray *aa = [[NSMutableArray alloc] initWithObjects:_cell.select, @0, nil];
//        [mArr addObject:aa];
//    }
//    [self.goodIdArr addObject:[model valueForKey:@"goods_id"]];
    
    // 如果商品数是一，不可以点击-
    /*
    if (self.selectArr.count > 0) {
        NSMutableArray *ar = self.selectArr[indexPath.section];
        // 同步
        if ([self.selectArr[indexPath.section][0][1] isEqual:@1]) {
            _cell.select.selected = YES;
            
            [ar[indexPath.row][1] replaceObjectAtIndex:1 withObject:@1];
        }
        else{
            _cell.select.selected = NO;
            [ar[indexPath.row][1] replaceObjectAtIndex:1 withObject:@0];
        }
    }
     */
    
    
    return _cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cartArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dict = self.cartArr[section];
    NSArray *arr = dict[@"goodslist"];
    
    return arr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 2*SW(8)+20;
}

//    设置分区高度 也可以使用代理方法
//_tableView.sectionHeaderHeight = 30;
//   tableView代理方法 设置分区高度（可以根据不同分区设置不同高度等实现自定义）
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 41;
}
//  自定义分区头的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString * identy = @"head";
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    if (!hf) {
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
        //        hf.backgroundColor = kWhiteColor;
    }
    if (hf.subviews.count >= 1) {
        [hf removeAllSubViews];
    }
    NSDictionary *shop = self.cartArr[section][@"shop"];
    NSLog(@"%ld",(long)section);
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [hf addSubview:btn];
    //        [btn setImage:[IMAGE(@"placeHolder") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [btn setImage:IMAGE(@"shop_car_unchose") forState:UIControlStateNormal];
    [btn setImage:IMAGE(@"shop_car_chose") forState:UIControlStateSelected];
    //        [btn addTarget:self action:@selector(storeClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = section+1000;
    
    btn.frame = CGRectMake(10, 5, 30, 30);
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(btn.x+btn.width+10, 5, 30, 30)];
    [hf addSubview:img];
    [img sd_setImageWithURL:[NSURL URLWithString:shop[@"photo"]] placeholderImage:IMAGE(@"placeHolder")];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(img.x+img.width+5, 0, SCREEN_WIDTH-100, 40)];
    [hf addSubview:title];
    title.text = shop[@"shop_name"];
    title.font = kUHSystemFontWithSize(12);
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 1)];
    [hf addSubview:view];
    view.backgroundColor = kLightGrayColor;
    return hf;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section < self.cartArr.count-1) {
        return 10;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    static NSString * identy = @"foot";
    UITableViewHeaderFooterView * fv = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    if (fv) {
        fv = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:identy];
//        fv.backgroundColor = UISeparatedColorRGB;
    }
    return fv;
}
- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = UISeparatedColorRGB;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = kWhiteColor;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
}

#pragma mark ==========响应方法==========
- (void)GETMallCart {
    [[NetworkTool sharedTool] requestWithName:@"获取购物车商品" URLString:APIMallsCarts parameters:nil method:@"GET" callBack:^(id responseObject) {
        [self.cartArr removeAllObjects];
        [self.cartArr addObjectsFromArray:responseObject[@"data"]];
        for (int i = 0; i < self.cartArr.count; i++) {
            NSMutableArray *mArr = [[NSMutableArray alloc] init];
            [self.selectArr addObject:mArr];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView.mj_header endRefreshing];
            [_tableView reloadData];
        });
    }];
}

- (void)navRightClick:(id)sender {
    NSLog(@"点击导航栏右按钮");
    
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"编辑"]) {
        self.navigationItem.rightBarButtonItem.title = @"完成";
        _goodMoney.hidden = YES;
        [_payment setTitle:@"删除" forState:UIControlStateNormal];
    }
    else {
        self.navigationItem.rightBarButtonItem.title = @"编辑";
        _goodMoney.hidden = NO;
        [_payment setTitle:@"结算" forState:UIControlStateNormal];
    }
}
// 点击商户
/*
- (void)storeClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    
    NSMutableArray *arr = self.selectArr[sender.tag-1000];
    
    NSLog(@"====%@", arr);
    
    for (NSMutableArray *a in arr) {
        UIButton *btn = a[0];
        NSNumber *isS = a[1];
//        isS = !isS;
        if ([isS  isEqual:@1]) {
            isS = @0;
            btn.selected = NO;
        }
        else{
            isS = @1;
            
            btn.selected = YES;
        }
        
//        [a insertObject:isS atIndex:1];
        [a replaceObjectAtIndex:1 withObject:isS];
        
    }
}
 */
// 点击商品
- (void)goodClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
//    for (NSMutableArray *a in arr) {
//        UIButton *btn = a[0];
//        NSNumber *isS = a[1];
//        //        isS = !isS;
//        if ([isS  isEqual:@1]) {
//            isS = @0;
//            btn.selected = NO;
//        }
//        else{
//            isS = @1;
//            
//            btn.selected = YES;
//        }
//        
//        //        [a insertObject:isS atIndex:1];
//        [a replaceObjectAtIndex:1 withObject:isS];
//        
//    }
}


// 懒加载
- (NSMutableArray *)cartArr {
    if (_cartArr == nil) {
        _cartArr = [[NSMutableArray alloc] init];
    }
    return _cartArr;
}
- (NSMutableArray *)selectArr {
    if (_selectArr == nil) {
        _selectArr = [[NSMutableArray alloc] init];
    }
    return _selectArr;
}
- (NSMutableArray *)goodIdArr {
    if (_goodIdArr == nil) {
        _goodIdArr = [[NSMutableArray alloc] init];
    }
    return _goodIdArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
